#!/usr/bin/env python
from tempfile import mkstemp
from shutil import move
from os import remove, close
from os import system
def replace(file_path, pattern, subst, count):
    #Create temp file
    fh, abs_path = mkstemp()
    new_file = open(abs_path,'w')
    old_file = open(file_path)
    print(old_file)
    for line in old_file:
        new_file.write(line.replace(pattern, subst, count))
    #close temp file
    new_file.close()
    close(fh)
    old_file.close()
    #Remove original file
    remove(file_path)
    #Move new file
    move(abs_path, file_path)

#import fileinput
#import sys
#def replaceAll(file,searchExp,replaceExp,count):
#    for line in fileinput.input(file, inplace=1):
#        if searchExp in line:
#            line = line.replace(searchExp,replaceExp,count)
#        sys.stdout.write(line)


import os
if os.path.exists("cscope.file"):
  os.remove("cscope.file")

if os.path.exists("tagsPerl"):
  os.remove("tagsPerl")

findcmd = "find . -name '*.pl' -o -name '*.pm' -o -name '*.plx' -o -name '*.perl'> cscope.files"
os.system(findcmd)
absPath = os.path.abspath(".")

print(findcmd,"under ", absPath)
replace("cscope.files",".",absPath,1)
print("generate cscope database:cscope.out cscope.in.out cscope.po.out")
os.system("cscope -bkq")
print("generate ctags database for Perl:tagsPerl")
os.system("ctags -a -f tagsPerl -F --fields=+imnlSfkst --language-force=Perl -L cscope.files --totals=yes ")

